<template>
  <div>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索 gutter间隙-->
      <el-row :gutter="20">
        <el-col :span="10">
          <!-- 搜索 -->
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogFormVisible = true">
            添加用户
          </el-button>
          <!-- 隐藏添加用户表单 -->
          <el-dialog
            title="添加用户"
            :visible.sync="dialogFormVisible"
            @close="resetForm"
          >
            <el-form
              :model="adduserForm"
              :rules="adduserRules"
              ref="adduserFormRef"
            >
              <!-- 用户名 -->
              <el-form-item
                label="用户名"
                :label-width="formLabelWidth"
                prop="username"
              >
                <el-input
                  v-model="adduserForm.username"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <!-- 密码 -->
              <el-form-item
                label="密码"
                :label-width="formLabelWidth"
                prop="password"
              >
                <el-input
                  v-model="adduserForm.password"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <!-- 邮箱 -->
              <el-form-item
                label="邮箱"
                :label-width="formLabelWidth"
                prop="email"
              >
                <el-input
                  v-model="adduserForm.email"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
              <!-- 电话 -->
              <el-form-item
                label="电话"
                :label-width="formLabelWidth"
                prop="mobile"
              >
                <el-input
                  v-model.number="adduserForm.mobile"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="resetForm">取 消</el-button>
              <el-button type="primary" @click="submituserForm">
                确 定
              </el-button>
            </div>
          </el-dialog>
          <!-- 隐藏用户结束 -->
        </el-col>
      </el-row>
      <!-- 列表 data数据源-->
      <el-table border style="width: 100%" :data="userList">
        <!-- 索引 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 状态 slot-scope具名插槽-->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- slot-scope="scope"{{ scope.row }} -->
            <!-- <span>{{ scope.row }}</span> -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 隐藏域 -->
            <el-dialog
              title="修改用户"
              :visible.sync="edituserFormVisible"
              @close="showEditDialogClose"
            >
              <el-form
                :model="edituserForm"
                :rules="edituserRules"
                ref="editformref"
              >
                <el-form-item label="用户名" :label-width="formLabelWidth">
                  <el-input
                    v-model="edituserForm.username"
                    autocomplete="off"
                    :disabled="true"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="邮箱"
                  :label-width="formLabelWidth"
                  prop="email"
                >
                  <el-input
                    v-model="edituserForm.email"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  label="手机"
                  :label-width="formLabelWidth"
                  prop="mobile"
                >
                  <el-input
                    v-model="edituserForm.mobile"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="edituserFormVisible = false">
                  取 消
                </el-button>
                <el-button type="primary" @click="editUser">
                  确 定
                </el-button>
              </div>
            </el-dialog>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteuser(scope.row)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <!-- 提示 -->
            <el-tooltip
              effect="dark"
              content="添加角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totals"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    // 电话号码验证
    var contactPhone = (rule, value, callback) => {
      if (value) {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      } else {
        return callback(new Error('请输入手机号'))
      }
    }
    return {
      // 获取用户列表
      queryInfo: {
        query: '',
        // 当前页码值
        pagenum: 1,
        // 每页显示多少
        pagesize: 2
      },
      userList: [],
      totals: 0,
      // 隐藏表单 添加用户
      dialogFormVisible: false,
      adduserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户
      edituserFormVisible: false,
      edituserForm: {},
      formLabelWidth: '80px',
      adduserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在6-12个字符', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            validator: contactPhone,
            trigger: 'blur'
          }
        ]
      },
      // 修改用户
      edituserRules: {
        email: [
          {
            required: true,
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['change']
          }
        ],
        mobile: [
          {
            required: true,
            validator: contactPhone,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    getUserList() {
      // 请求参数，用params
      this.$ajax
        .get('users', {
          params: this.queryInfo
        })
        .then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('获取数据失败')
          }
          this.userList = res.data.data.users
          this.totals = res.data.data.total
          // console.log(this.totals)
        })
    },
    // 监听pagesize就是每页条数
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      // console.log(`每页 ${val} 条`)
      this.getUserList()
    },
    // 页码值改变
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      // 需要再请求数据
      this.getUserList()
    },
    // 管理的值状态 动态id怎么设置
    async changStatus(val) {
      console.log(val)
      const { data: res } = await this.$ajax.put(
        `users/${val.id}/state/${val.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        // 都已经失败了，把页面的状态重置回去
        val.mg_state = !val.mg_state
        return this.$message.error('状态更改失败')
      }
      this.$message.success('更新状态成功')
    },
    // 添加用户  取消按钮 移除填写的结果
    resetForm() {
      console.log(this)
      this.$refs.adduserFormRef.resetFields()
      this.dialogFormVisible = false
    },
    // 添加用户提交
    async submituserForm() {
      const valid = await this.$refs.adduserFormRef.validate()
      console.log('验证结果' + valid)
      if (!valid) return this.$message.error('验证失败')
      const { data: res } = await this.$ajax.post('users', this.adduserForm)
      // console.log(res)
      if (res.meta.status !== 201) return this.$message.error('用户已经存在')
      this.getUserList()
      this.$message.success('成功创建用户')
      // 创建成功后移除数据
      this.$refs.adduserFormRef.resetFields()
    },
    // 根据id删除用户
    deleteuser(val) {
      // console.log(val.id)
      this.$confirm('此操作将永久删除这个用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$ajax.delete(`users/${val.id}`)
          if (res.meta.status === 200) {
            this.getUserList()
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })

      //
    },
    // 根据id查询用户
    async showEditDialog(id) {
      const { data: res } = await this.$ajax.get('users/' + id)
      this.edituserFormVisible = true
      // console.log(res)
      if (res.meta.status === 200) {
        this.edituserForm = res.data
        // console.log(this.edituserForm)
      } else {
        this.$message.error('出错了请重试')
      }
    },
    // 确定 编辑用户
    editUser() {
      this.$refs.editformref.validate(async valid => {
        if (!valid) {
          return this.$message.error('格式验证错误')
        }
        //  发起请求
        const { data: res } = await this.$ajax.put(
          'users/' + this.edituserForm.id,
          {
            id: this.edituserForm.id,
            email: this.edituserForm.email,
            mobile: this.edituserForm.mobile
          }
        )
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.getUserList()
      })
      this.edituserFormVisible = false
    },
    // 关闭重置表单 监听修改用户对话框的关闭事件
    showEditDialogClose() {
      this.$refs.editformref.resetFields()
    }
  },

  created() {
    // 首屏展示
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
.el-input {
  outline: none;
}
.el-table {
  margin-top: 20px;
  font-size: 13px;
}
// 分页条
.el-pagination {
  margin-top: 20px;
}

.el-button {
  margin-left: 5px !important;
}
</style>
